package DB_file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import relation.Field;
import relation.Table;

import java.io.*;

/**
 * 将表类写入文件
 * @author cgl-22341129
 */
public class JsonWriter {
    private String charsetName;
    private String filepath;
    private JSONObject jsonObject;

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    /**
     * 将table类写入json文件
     * @param table 需要序列化的table类
     */
    public void writeTable(Table table){
        this.write(JSON.toJSONString(table));
    }
    private void write(String jstr){
       File file=new File(this.filepath);
       if(!file.exists()) {
           try {
               file.createNewFile();
           } catch (IOException e) {
               System.out.println("创建文件失败");
               throw new RuntimeException(e);
           }
       }
        FileInputStream fileInputStream= null;
        try {

            FileOutputStream fileOutputStream=new FileOutputStream(file);
            OutputStreamWriter writer=new OutputStreamWriter(fileOutputStream,"UTF-8");
            writer.append(jstr);

            writer.close();
            fileOutputStream.close();

        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public JsonWriter(String filepath) {
        this.filepath = filepath;
    }

}
